//
//  DHCommentController.m
//  精品酒店
//
//  Created by DIANGHONG on 2018/5/16.
//  Copyright © 2018年 DIANGHONG. All rights reserved.
//

#import "DHCommentController.h"

@interface DHCommentController ()<DidChangedStarDelegate,UIActionSheetDelegate, UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UITextView *evaTextView;
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *evaImgButtons; //评价照片的按钮数组
@property(nonatomic ,strong)UIButton *currentButton; //记录当前选中按钮
@property(nonatomic ,strong)UIButton *imgButton; //记录按钮图像
@property(nonatomic ,strong)DHNavbarView *navbar; // 导航栏
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *commentStarHCons;
@property (weak, nonatomic) IBOutlet UIView *evaStarView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *postComBottomCons;
@property(nonatomic ,strong)HYBStarEvaluationView *starView;

@property(nonatomic,strong) UIImagePickerController *imagePicker; //声明全局的UIImagePickerController

@end

@implementation DHCommentController
#pragma mark： - 发表评价按钮监听
- (IBAction)postButtonClick:(UIButton *)sender
{
    if (!self.evaTextView.hasText) {
        [SVProgressHUD showInfoWithStatus:@"请输入评价内容"];
        return;
    }
 //   UIImage *img = [UIImage imageNamed:@"jia"];
    NSMutableArray<NSData*> *arrayM = [NSMutableArray array];
    [self.evaImgButtons enumerateObjectsUsingBlock:^(UIButton *obj, NSUInteger idx, BOOL * _Nonnull stop)
     {
         if (obj.currentImage) {
             [arrayM addObject:UIImagePNGRepresentation(obj.currentImage)];
         }
     }];
    
    
    self.postEvaParam[@"image_*"] = arrayM.copy;
    
    self.postEvaParam[@"scores"] = [NSString stringWithFormat:@"%.2f",self.starView.actualScore];
    
    [DHNetworkManager.shareManager postEvaWithParams:self.postEvaParam.copy completion:^(BOOL isSuccess, NSString *statusInfo)
    {
        if (!isSuccess) {
            [SVProgressHUD showErrorWithStatus:statusInfo];
            return ;
        }
        
        [SVProgressHUD showSuccessWithStatus:statusInfo];
        [self.navigationController popViewControllerAnimated:true];
    }];
}
// lazy navbar
- (DHNavbarView *)navbar{
    if (!_navbar)
    {
        __weak typeof(self) WeakSelf = self;
        CGRect frame;
        frame = KIsiPhoneX ? CGRectMake(0, 0, kScreenWidth, 88) : CGRectMake(0, 0, kScreenWidth, 64);
        _navbar = [DHNavbarView navbarViewWithFrame:frame title:@"发表评价" isHiddenReturn:NO];
        _navbar.popButtonClickBlock = ^{
            [WeakSelf.navigationController popViewControllerAnimated:true];
        };
    }
    return _navbar;
}

- (void)viewDidLoad {
    [super viewDidLoad];
   // self.navigationController.navigationBar.hidden = false;
    [self.view addSubview:self.navbar];
    //[self.view setins]
    self.commentStarHCons.constant = CGRectGetMaxY(self.navbar.frame) + 16;
    [self.view layoutIfNeeded];

    
    //监听键盘的操作：
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    self.starView = [[HYBStarEvaluationView alloc]initWithFrame:self.evaStarView.bounds numberOfStars:5 isVariable:YES];
    
    self.starView.isContrainsHalfStar = YES;//是否包含半颗星，默认为NO
    self.starView.fullScore = 5;
    self.starView.actualScore = 5;
    self.starView.delegate = self;
    [self.evaStarView addSubview:self.starView];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:true];
}
- (void)dealloc
{
    [NSNotificationCenter.defaultCenter removeObserver:self];
}
#pragma mark: - 选择评价照片点击事件
- (IBAction)selectedImgClick:(UIButton *)sender
{
    self.currentButton.selected = false;
    sender.selected = YES;
    self.currentButton = sender;
    //自定义消息框
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"选择" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册选择", nil];
    sheet.tag = 2550;
    //显示消息框
    [sheet showInView:self.view];
}
#pragma mark -消息框代理实现-
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (actionSheet.tag == 2550) {
        NSUInteger sourceType = 0;
        // 判断系统是否支持相机
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            imagePickerController.delegate = self; //设置代理
            imagePickerController.allowsEditing = YES;
            imagePickerController.sourceType = sourceType; //图片来源
            if (buttonIndex == 0) {
                //拍照
                sourceType = UIImagePickerControllerSourceTypeCamera;
                imagePickerController.sourceType = sourceType;
                [self presentViewController:imagePickerController animated:YES completion:nil];
                
                
            }else if (buttonIndex == 1) {
                //相册
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                imagePickerController.sourceType = sourceType;
                [self presentViewController:imagePickerController animated:YES completion:nil];
                
            }else if (buttonIndex == 2){
                
                return;
            }
        }else {
            sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            imagePickerController.sourceType = sourceType;
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }
    }
}
#pragma mark -实现图片选择器代理-（上传图片的网络请求也是在这个方法里面进行，这里我不再介绍具体怎么上传图片）
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^{}];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; //通过key值获取到图片
    
    //上传图片到服务器--在这里进行图片上传的网络请求，这里不再介绍
    //  ......
    [[self.evaImgButtons valueForKey:@"selected"] enumerateObjectsUsingBlock:^(NSNumber *obj, NSUInteger idx, BOOL * _Nonnull stop)
     {
         if (obj.boolValue) {
             [(UIButton *)self.evaImgButtons[idx] setImage:image forState:UIControlStateNormal];
         }
     }];
}
#pragma mark: - 监听键盘弹出通知
- (void)keyboardWillChangeFrame:(NSNotification *)n
{
   // NSLog(@"%@",n.userInfo);
    //注意，字典里存放的都是对象，要把对象转为CGRect结构体，使用CGRectValue方法。
    CGRect keyboardFrame = [n.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat duration = [n.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    CGFloat offsetY = keyboardFrame.origin.y - self.view.frame.size.height;
    
    self.postComBottomCons.constant = -offsetY;
    NSLog(@"%f",offsetY);
    [UIView animateWithDuration:duration animations:
     ^{
         [self.view layoutIfNeeded];
    }];
}

- (void)didChangeStar
{
    NSLog(@"%f",self.starView.actualScore);
}
@end
